package com.codingday.app;

import java.util.Calendar;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

public class MyLocationManager implements LocationListener{

	private Location location = null;
	private LocationManager manager = null;
	private String bestProvider = null;
	private String provider = "";
	Criteria criteria = null;
	boolean isEnabled = false;
	boolean isProviderEnabled = false;
	//boolean hasLocation = false;
	
	//private LocationListener gpsListener = null;
	//private LocationListener networkListener = null;
	
	
	public MyLocationManager(Context context){
		manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		initBestProvider();
		//initLocationListener();
		
		location = manager.getLastKnownLocation(bestProvider);		
		if(location == null){
			Log.i("MyLocationManager","location is null");
		}
		//manager.requestLocationUpdates(bestProvider, 60000, 0, this);
		location = manager.getLastKnownLocation(bestProvider);
		//Enable(60000,10);
		//setListenerUpdateTime(60000,0);
		//manager.requestLocationUpdates(bestProvider, 60000, 0, this);
		//Enable();
	}
	
	public void initBestProvider(){
		/*
		criteria = new Criteria();
		
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
		
		bestProvider = manager.getBestProvider(criteria, true);
		*/
		bestProvider = LocationManager.NETWORK_PROVIDER;
	}
	
	
	public Location getMyLocation(){
		Log.i("MyLocationManager","getMyLocation");
		if(location == null){
			location = manager.getLastKnownLocation(bestProvider);
		}
		return location;
	}
	
	
	

	public void Enable(int updateTime, int minDistance){
		Disable();
		initBestProvider();
		manager.requestLocationUpdates(bestProvider, updateTime, minDistance, this);
	
		isEnabled = true;
	}
	
	public void Disable(){
		if(isEnabled){
			manager.removeUpdates(this);
		}
		isEnabled = false;
	}

	public String getProvider(){
		return provider;
	}
	public String getBestProvider(){
		return bestProvider;
	}
	public boolean isProviderEnabled(){
		return isProviderEnabled;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		this.location = location;
		//hasLocation = true;
		//manager.removeUpdates(this);
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		
	}
	
}
